package com.flowershop.servlet;

import com.flowershop.model.Flower;
import com.flowershop.model.Category;
import com.flowershop.service.FlowerService;
import com.flowershop.service.CategoryService;
import com.flowershop.service.UserService;
import com.flowershop.model.User;
import com.flowershop.service.CartService;
import com.flowershop.model.CartItem;
import com.flowershop.service.OrderService;
import com.flowershop.model.Order;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/shop/*")
public class ShopServlet extends HttpServlet {
    private FlowerService flowerService = new FlowerService();
    private CategoryService categoryService = new CategoryService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if ("/login".equals(pathInfo)) {
            // 显示登录页面
            request.getRequestDispatcher("/WEB-INF/views/shop/login.jsp").forward(request, response);
        } else if ("/logout".equals(pathInfo)) {
            // 处理退出登录
            request.getSession().invalidate();
            response.sendRedirect(request.getContextPath() + "/shop");
        } else if ("/cart".equals(pathInfo)) {
            // 检查用户是否登录
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect(request.getContextPath() + "/shop/login");
                return;
            }
            
            // 获取购物车内容
            CartService cartService = new CartService();
            List<CartItem> cartItems = cartService.getCartItems(user.getId());
            request.setAttribute("cartItems", cartItems);
            request.getRequestDispatcher("/WEB-INF/views/shop/cart.jsp").forward(request, response);
            return;
        } else if ("/orders".equals(pathInfo)) {
            // 检查用户是否登录
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect(request.getContextPath() + "/shop/login");
                return;
            }
            
            // 获取用户订单列表
            OrderService orderService = new OrderService();
            List<Order> orders = orderService.getOrdersByUserId(user.getId());
            request.setAttribute("orders", orders);
            request.getRequestDispatcher("/WEB-INF/views/shop/orders.jsp").forward(request, response);
            return;
        } else if ("/checkout".equals(pathInfo)) {
            // 检查用户是否登录
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect(request.getContextPath() + "/shop/login");
                return;
            }
            
            // 创建订单
            OrderService orderService = new OrderService();
            Order order = orderService.createOrderFromCart(user.getId());
            
            if (order != null) {
                response.sendRedirect(request.getContextPath() + "/shop/orders");
            } else {
                response.sendRedirect(request.getContextPath() + "/shop/cart");
            }
            return;
        } else {
            // 获取分类列表
            List<Category> categories = categoryService.getAllCategories();
            request.setAttribute("categories", categories);
            
            // 获取商品列表
            String categoryId = request.getParameter("categoryId");
            List<Flower> flowers;
            if (categoryId != null && !categoryId.isEmpty()) {
                flowers = flowerService.getFlowersByCategory(Integer.parseInt(categoryId));
            } else {
                flowers = flowerService.getAllFlowers();
            }
            request.setAttribute("flowers", flowers);
            
            // 转发到商城首页
            request.getRequestDispatcher("/WEB-INF/views/shop/index.jsp").forward(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        response.setContentType("application/json;charset=UTF-8");
        
        if ("/login".equals(pathInfo)) {
            // 处理登录请求
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            
            UserService userService = new UserService();
            User user = userService.login(username, password);
            
            if (user != null) {
                request.getSession().setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/shop");
            } else {
                request.setAttribute("error", "用户名或密码错误");
                request.getRequestDispatcher("/WEB-INF/views/shop/login.jsp").forward(request, response);
            }
        } else if ("/cart/add".equals(pathInfo)) {
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.getWriter().write("{\"success\":false,\"message\":\"请先登录\"}");
                return;
            }
            
            CartItem item = new CartItem();
            item.setUserId(user.getId());
            item.setFlowerId(Integer.parseInt(request.getParameter("flowerId")));
            item.setQuantity(Integer.parseInt(request.getParameter("quantity")));
            
            CartService cartService = new CartService();
            boolean success = cartService.addToCart(item);
            
            response.getWriter().write("{\"success\":" + success + "}");
            return;
        } else if ("/cart/update".equals(pathInfo)) {
            Integer id = Integer.parseInt(request.getParameter("id"));
            Integer quantity = Integer.parseInt(request.getParameter("quantity"));
            
            CartService cartService = new CartService();
            boolean success = cartService.updateQuantity(id, quantity);
            
            response.getWriter().write("{\"success\":" + success + "}");
            return;
        } else if ("/cart/remove".equals(pathInfo)) {
            Integer id = Integer.parseInt(request.getParameter("id"));
            
            CartService cartService = new CartService();
            boolean success = cartService.removeFromCart(id);
            
            response.getWriter().write("{\"success\":" + success + "}");
            return;
        } else if ("/order/status".equals(pathInfo)) {
            Integer orderId = Integer.parseInt(request.getParameter("orderId"));
            String status = request.getParameter("status");
            
            OrderService orderService = new OrderService();
            boolean success = orderService.updateOrderStatus(orderId, status);
            
            response.getWriter().write("{\"success\":" + success + "}");
            return;
        }
    }
} 